<?php 
    if (isset($_COOKIE['userid']) && isset($_COOKIE['usermd5']))
    {
        require('config.php');
        //get the fav video number n, which can be used to draw n loading images in ImageWall
        if ($_POST && $_POST['type'] == '0')
        {
            $favType = $_POST['favType'];
    		$stmt = $connection->prepare("select count(*) from user_fav where user_id=? and fav_type=?");
    		$stmt->bind_param("ss", $_COOKIE['userid'], $favType);
    		$stmt->execute();
            $stmt->bind_result($count);
            $stmt->fetch();
            echo $count; 
            $connection->close();
        }
        else
        {
            $favType = $_POST['favType'];
            $start = $_POST['start'];
            //every time load 20 images
            $stmt = $connection->stmt_init();
    		$stmt->prepare("select video_id, fav_time from user_fav where user_id=? and fav_type=? order by fav_time desc limit " . $start . ", 20");
    		$stmt->bind_param("ss", $_COOKIE['userid'], $favType);
    		$stmt->execute();
            $stmt->bind_result($video_id, $fav_time);
    		$result = '{"images":[';
            $videos = array();
            $fav_times = array();
            while ($stmt->fetch()) 
            {
                array_push($videos, $video_id);
                array_push($fav_times, $fav_time);
            }
            $stmt->close();
            $num = count($videos);
            //get detail information to every video
            for ($i = 0; $i < $num; ++$i)
            {
                $stmt = $connection->prepare("select title, imagelink, playlink, duration from video_info where id=? limit 1");
    		    $stmt->bind_param("s", $videos[$i]);
    		    $stmt->execute();
                $stmt->bind_result($title, $imagelink, $playlink, $duration);
                $stmt->fetch();
                $hour = floor($duration / 3600);
                $duration = $duration % 3600;
                $minute = floor($duration / 60);
                $second = $duration % 60;
                $title = str_replace("\"","\\\"",$title);
                $time = $hour . ':' . $minute . ':' . $second;
                $result = $result . '{"src":"' . $imagelink . '","title":"' . $title . '", "playlink":"'. $playlink . '", "href":"' . $videos[$i] . '", "duration":"' . $time . '", "fav_time":"' . $fav_times[$i] . '"},';
                $stmt->close();
                
            }
    		if ($result[strlen($result) - 1] == ',')
    		{
    			$result = substr($result, 0, strlen($result) - 1);	
    		}
    		$result = $result . ']}';
            echo $result;
            $connection->close();
        }
    }
    else
    {
        echo "NOUSER";
    }
?> 
